<!-- src/views/Home.vue -->
<script setup>
// import { hometStatistics } from '@/apis/workOrder';
import { onMounted, reactive,ref,computed} from 'vue';
import * as echarts from 'echarts/core'
import { LineChart, PieChart } from 'echarts/charts'
import { getHomeStats,getWorkOrderStatusStats,getWorkOrderTypeStats,getWorkOrderTrendStats} from '@/apis/statisticsAPI';
import {
  TitleComponent,
  TooltipComponent,
  GridComponent,
  LegendComponent
} from 'echarts/components'
import { CanvasRenderer } from 'echarts/renderers'

import { ElMessage } from 'element-plus';

// 注册必须的组件
echarts.use([
  TitleComponent,
  TooltipComponent,
  GridComponent,
  LineChart,
  PieChart,
  LegendComponent,
  CanvasRenderer
])

// 状态管理
const statisticsTop = reactive({});
const statisticsUn=reactive({});

// 图表引用

const statusColors = {
  '进行中': '#4888FF',
  '已指派': '#20C997',
  '已完成': '#FFC107',
  '待确认': '#FF6B6B',
  '待结算': '#9C27B0',
  '待评价': '#6C757D'
};

// 2.2 工单类型颜色
const typeColors = {
  '维修类': '#1E88E5',
  '安装类': '#FF9800',
  '咨询类': '#4CAF50',

};
const acitiveStatType=ref('status');
const statData = ref([]); // 存储转换后的图表数据
const res=ref();
const getWorkorderSta = async () => {

  try {
    // 调用对应接口
    if (acitiveStatType.value === 'status') {
      res.value = await getWorkOrderStatusStats();
    } else {
      res.value = await getWorkOrderTypeStats();
    }
    console.log('接口完整响应:', res.value);
    // 检查接口响应是否正常
    if (!res.value || !res.value.data) {
      throw new Error('接口返回格式异常');
    }

    // 处理数据（根据后端实际code调整，通常是200）
    if (res.value.code === 0) {
      const rawData = res.value.data;

      // 验证原始数据是否有效
      if (typeof rawData !== 'object' || rawData === null) {
        throw new Error('后端返回数据格式错误，应为对象');
      }

      // 转换数据格式
      statData.value = Object.entries(rawData).map(([key, value]) => {
        // 确保value是数字且不为0
        const numValue = Number(value);
        if (isNaN(numValue) || numValue <= 0) {
          console.warn(`数据${key}无效，已修正为1`, value);
          return {
            name: key,
            value: 1, // 无效值修正为1，避免饼图空白
            color: acitiveStatType.value === 'status'
              ? statusColors[key] || '#CCCCCC'
              : typeColors[key] || '#CCCCCC'
          };
        }

        // 正常数据
        return {
          name: key,
          value: numValue,
          color: acitiveStatType.value === 'status'
            ? statusColors[key] || '#CCCCCC'
            : typeColors[key] || '#CCCCCC'
        };
      });

      console.log('转换后的数据:', statData.value); // 调试用
    } else {
      throw new Error(`接口错误: ${res.value.data.msg || '未知错误'}`);
    }
  } catch (error) {
    console.error('获取统计数据失败:', error);
    ElMessage.error(`加载失败: ${error.message}`);
    statData.value = []; // 出错时清空数据
  }
};
const categoryOption = computed(() => ({
  title: {
    text: acitiveStatType.value === 'type' ? '工单类型统计' : '工单状态统计',
    left: 'left',
    textStyle: { fontSize: 16, fontWeight: 'normal' }
  },
  tooltip: {
    trigger: 'item',
    formatter: '{a} <br/>{b}: {c} ({d}%)'
  },
  legend: {
    orient: 'vertical',
    left: 'bottom',
    top: 'center',
    data: statData.value.map(i => i.name)
  },
  series: [
    {
      name: acitiveStatType.value === 'type' ? '工单类型' : '工单状态',
      type: 'pie',
      radius: ['40%', '70%'],
      data: statData.value.map(i => ({ name: i.name, value: i.value })),
      color: ['#4888FF', '#20C997', '#FFC107', '#FF6B6B', '#9C27B0', '#6C757D'], // 固定颜色
      itemStyle: { borderRadius: 4, borderColor: '#fff', borderWidth: 2 },
      emphasis: { label: { show: true, fontSize: 16, fontWeight: 'bold' } }
    }
  ]
}));
// 5. 切换统计维度时重新加载数据
const handleStatTypeChange = () => {
  getWorkorderSta();
};






const timeRange = ref('seven'); // 默认七天
const trendData = ref({ dates: [], counts: [] });
const getDaysByRange = (range) => {
  return range === 'seven' ? 7 : 14;
};
const fetchTrendData = async () => {
  try {
    const days = getDaysByRange(timeRange.value);
    const res = await getWorkOrderTrendStats(days);
    if (res.code === 0) {
      const rawData = res.data || [];
      trendData.value = {
        dates: rawData.map(item => formatDate(item.date)),
        counts: rawData.map(item => Number(item.count) || 0)
      };
      console.log('格式化后的趋势数据：', trendData.value);
    } else {
      throw new Error(`接口错误：${res.data.msg || '获取趋势数据失败'}`);
    }
  } catch (error) {
    console.error('获取工单趋势失败：', error);
    trendData.value = { dates: [], counts: [] }; // 错误时重置
  }
};

// 5. 日期格式化工具（适配后端yyyy-MM-dd格式）
const formatDate = (dateStr) => {
  // 分割日期字符串："2025-09-26" → ["2025", "09", "26"]
  const [year, month, day] = dateStr.split('-');
  // 返回"月-日"格式（如"09-26"），若需显示年份可改为`${month}-${day}(${year.slice(2)})`
  return `${month}-${day}`;
};

// 6. 切换时间范围时重新请求数据
const handleTimeRangeChange = (value) => {
  timeRange.value = value;
  fetchTrendData(); // 切换后立即更新数据
};
const trendOption = computed(() => ({
  title: {
    text: '工单趋势',
    left: 'left',
    textStyle: { fontSize: 16, fontWeight: 'normal' }
  },
  tooltip: {
    trigger: 'axis',
    backgroundColor: 'rgba(255,255,255,0.9)',
    borderColor: '#ddd',
    borderWidth: 1,
    textStyle: { color: '#333' },
    // 适配单条数据的Tooltip显示
    formatter: (params) => {
      if (!params || params.length === 0) return '';
      const { name, value, seriesName } = params[0];
      return `<div style="font-weight:bold">${name}</div>
              <div>${seriesName}：${value} 单</div>`;
    }
  },
  legend: {
    data: ['工单数量'], // 单图例（匹配series.name）
    top: 30,
    right: 10
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '3%',
    containLabel: true // 确保坐标轴标签不被截断
  },
  xAxis: {
    type: 'category',
    boundaryGap: false, // 取消坐标轴留白，让线条紧贴左右
    data: trendData.value.dates || [],
    axisLabel: {
      rotate: 30, // 日期标签旋转30度，避免重叠
      fontSize: 12
    }
  },
  yAxis: {
    type: 'value',
    min: 0, // Y轴最小值设为0，确保0值正常显示（不被压缩）
    max: Math.max(...trendData.value.counts, 5) || 5, // 最大刻度兜底5，避免数据全0时图表过矮
    axisLabel: {
      formatter: '{value} 单' // 显示单位，更直观
    },
    splitLine: {
      lineStyle: {
        color: 'rgba(0,0,0,0.05)' // 网格线淡化，提升美观度
      }
    }
  },
  series: [
    {
      name: '工单数量',
      type: 'line',
      data: trendData.value.counts || [], // 后端返回的count数组（含0）
      // 面积填充（可选，增强视觉效果）
      areaStyle: {
        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          { offset: 0, color: 'rgba(52, 152, 219, 0.3)' }, // 渐变起点
          { offset: 1, color: 'rgba(52, 152, 219, 0)' }    // 渐变终点（透明）
        ])
      },
      lineStyle: {
        color: '#3498db', // 线条颜色
        width: 2 // 线条粗细
      },
      itemStyle: {
        color: '#3498db', // 数据点颜色
        borderWidth: 2,
        borderColor: '#fff' // 数据点白色边框，增强辨识度
      },
      symbol: 'circle', // 数据点显示为圆形
      symbolSize: 8, // 数据点大小（0值也能清晰看见）
      emphasis: {
        symbolSize: 12 // 鼠标悬浮时数据点放大，提升交互体验
      }
    }
  ]
}));
onMounted(async()=>{
  getWorkorderSta();
  getWorkOrderTrendStats();
  try{
    //这是从后端拿数据，接口写好后取消注释
     const {data}=await getHomeStats();
     const{dataOverview,todoStats}=data;
     Object.assign(statisticsUn,dataOverview);
     Object.assign(statisticsTop,todoStats);

  }catch(e){
    console.error(e)
  }

})
</script>

<template>
  <div class="dashboard">
    <h2 class="section-title">待办事项</h2>
    <div class="todo-cards">
      <div class="card todo-card">待确认订单 <span class="count">{{ statisticsTop.pendingConfirm }}</span></div>
      <div class="card todo-card">指派工单 <span class="count">{{ statisticsTop.assigned }}</span></div>
      <div class="card todo-card">待结算工单 <span class="count">{{ statisticsTop.pendingSettlement }}</span></div>
      <div class="card todo-card">待评价工单 <span class="count">{{ statisticsTop.pendingEvaluation }}</span></div>
      <div class="card todo-card">进行中工单 <span class="count">{{ statisticsTop.inProgress }}</span></div>
    </div>

    <h2 class="section-title">数据概览</h2>
    <div class="data-cards">
      <div class="card data-card">工单总数 <span class="count">{{ statisticsUn.workOrderTotal }}</span></div>
      <div class="card data-card">本月新增 <span class="count">{{ statisticsUn.monthNew }}</span></div>
      <div class="card data-card">客户总数 <span class="count">{{ statisticsUn.customerTotal }}</span></div>
      <div class="card data-card">总收入 <span class="count">{{ statisticsUn.totalIncome }}</span></div>
      <div class="card data-card">总支出 <span class="count">{{ statisticsUn.totalExpenditure }}</span></div>
    </div>
       <div class="chart-container">
      <!-- 左侧：工单趋势图 -->
      <div class="chart-card">
        <div class="chart-header">
          <h2>工单趋势</h2>
          <el-radio-group v-model="timeRange" @change="handleTimeRangeChange" size="small">
            <el-radio-button label="seven">七天</el-radio-button>
            <el-radio-button label="forteen">十四天</el-radio-button>
          </el-radio-group>
        </div>
        <v-chart :option="trendOption" style="width: 100%; height: 350px;" />
      </div>

      <!-- 右侧：工单分类统计图 -->
      <div class="chart-card">
        <div class="chart-header">
          <h2>工单分类统计</h2>
          <el-radio-group size="small" v-model="acitiveStatType" @change="handleStatTypeChange">
            <el-radio-button label="type">按类型</el-radio-button>
            <el-radio-button label="status">按状态</el-radio-button>
          </el-radio-group>
        </div>
        <v-chart :option="categoryOption" style="width: 100%; height: 350px;" />
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">
/* 全局样式 */
* {
  margin: 0;

  padding: 0;
  box-sizing: border-box;
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}
/* 仪表盘内容 */
.dashboard {
  padding: 24px;
  margin-top: 3%;
}

.section-title {
  font-size: 18px;
  color: #333;
  margin-bottom: 16px;
  font-weight: 600;
  display: flex;
  align-items: center;
}

.section-title::after {
  content: '';
  flex: 1;
  height: 1px;
  background-color: #eee;
  margin-left: 16px;
}

/* 卡片容器 */
.todo-cards, .data-cards {
  display: flex;
  gap: 16px;
  margin-bottom: 24px;
  flex-wrap: wrap;
}

/* 卡片样式 */
.card {
  flex: 1;
  min-width: 160px;
  padding: 20px;
  border-radius: 8px;
  background-color: white;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;
  font-weight: 500;
  color: #555;
}

.card::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 4px;
  height: 100%;
}

.todo-card {
  border: 1px solid #f1c40f;
  cursor: pointer;
}

.todo-card::before {
  background-color: #f1c40f;
}

.todo-card:hover {
  transform: translateY(-5px) scale(1.02);
  box-shadow: 0 10px 20px rgba(241, 196, 15, 0.2);
}

.data-card {
  border: 1px solid #3498db;
}

.data-card::before {
  background-color: #3498db;
}
.data-card:hover {
  transform: translateY(-5px) scale(1.02);
  box-shadow: 0 10px 20px rgba(15, 38, 241, 0.2);
}

.count {
  display: block;
  font-size: 24px;
  font-weight: 700;
  margin-top: 8px;
}

.todo-card .count {
  color: #f39c12;
}

.data-card .count {
  color: #2980b9;
}
/* 图表容器样式 */
.chart-container {
  display: flex;
  gap: 24px;
  margin-top: 24px;
}

.chart-card {
  flex: 1;
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  padding: 20px;
  min-width: 300px;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.chart-header h2 {
  font-size: 16px;
  color: #333;
  font-weight: 600;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .chart-container {
    flex-direction: column;
  }
}
</style>
